/**
 * 表格扩展按钮click事件
 */
 import {toast } from 'nc-lightapp-front';
import { headSumHandle } from "./commonEvent";
import requestApi from '../requestApi';
import { setDefautValueAfterBodyAdd } from '../initTemplate';

// 查看发票
function handleInvioceShow(props,currentRow){
    let multiLang = props.MutiInit.getIntl(2011);
    let bxToInvoice = window.presetVar.bxToInvoice
    // 获取当前点击行的key
    let pk_erminvoice = currentRow[0].values.pk_erminvoice.value
    // 获取接口返回的发票对应关系数组 {"交通key":['11','33344','566']}
    let invioces = bxToInvoice && bxToInvoice[pk_erminvoice]
    // 获取发票列表
    let invoice_Detail = props.cardTable.getVisibleRows('invoice_Detail')
    let goalInvioce = [] //符合的发票
    // 从发票页签中找到交通点击行对应的发票列
    invioces &&invioces.forEach((itemInvoice,index) => {
        let test = []
        test = invoice_Detail.filter((item) => {
            return item.values.pk_erminvoice.value === itemInvoice
        })
        goalInvioce = [...goalInvioce,...test]
    })

    if(invioces && goalInvioce.length){
        let wrap = document.getElementsByName('anchor-invoice_Detail')[0]
        // 获取发票页签表格行
        let trs = Array.from(wrap.querySelectorAll('div.u-table-scroll div.u-table-body tr'))
        // 遍历发票页签所有行去除高亮样式
        trs.forEach((tr,index) => {
            tr.classList.remove('table-selected')
        })
        // 交通点击行相关连的发票
        let goalTrs = []
        goalInvioce.forEach((item,index) => {
            let oriTrs = []
            oriTrs = trs.filter((tr,index) => {
                return item.rowid === tr.dataset.rowKey
            })
            goalTrs = [...goalTrs,...oriTrs]
        })
        goalTrs.forEach((item) => {
            item.classList.remove('table-selected')
            setTimeout(() => {
                item.classList.add('table-selected')
            })
        })
        goalTrs[0].scrollIntoView({block:'end'})
    } else{
        toast({color:'warning',content:multiLang && multiLang.get("201101BXFP-0001")});
    }
}
// 查看明细
function handleShowDetail(props,currentRow){
    //获取发票对应关系
    let invoiceToBx = window.presetVar.invoiceToBx
    let oriRow = ''
    // 获取发票key
    let pk_erminvoice = currentRow[0].values.pk_erminvoice.value
    console.log('pk_erminvoice',pk_erminvoice)
    let pk_bx = invoiceToBx[pk_erminvoice][0] //取出住宿等pk

    // 遍历上方所有页签找到与发票相关联行
    Object.values(presetVar.body).forEach((body,index) => {
        let currentTb = document.getElementsByName('anchor-'+ body)[0]
        // 获取当前行的页签所有行元素
        let trs = Array.from(currentTb.querySelectorAll('div.u-table-scroll div.u-table-body tr'))
        trs.forEach((tr,index) => {
            tr.classList.remove('table-selected')
        })
        // 获取当前页签所有可见行
        let allRows = props.cardTable.getVisibleRows(body)
        // 排除发票页签自身
        if(body !== 'invoice_Detail' && body !== 'accrued_verify' && body !== 'er_bxcontrast'){
            // 遍历当前页签得到与发票点击行相关联的明细行
            oriRow = allRows.filter((item) => {
                return pk_bx === item.values.pk_erminvoice.value;
            });
            if (oriRow.length > 0) {
                // props.cardTable.focusRowByIndex(body,currentIndex)
                let currentTb = document.getElementsByName('anchor-' + body)[0];
                // 获取当前行的页签所有行元素
                let trs = Array.from(currentTb.querySelectorAll('div.u-table-scroll div.u-table-body tr'));
                // 从当前页签中获取对应明细行
                let curTrs = trs.filter((item) => {
                    return oriRow.some((row) => row.rowid === item.dataset.rowKey);
                });
                curTrs.forEach((item) => {
                    item.classList.remove('table-selected');
                    setTimeout(() => {
                        item.classList.add('table-selected');
                    }, 0);
                });
                // 滚动到对应位置
                curTrs[0].scrollIntoView({ block: 'end' });
            }
        }
    })

}
function tableExtendButtonClick() {
    let returnObj = {};
    for(let name in window.presetVar.body){
        let areaId = window.presetVar.body[name];
        returnObj[areaId +'_invoice_show']= (...args) => {
            console.log('pros',this.props)
            handleInvioceShow(this.props,args)
        }
        returnObj[areaId +'_show_detail']= (...args) => {
            console.log(args)
            handleShowDetail(this.props,args)
        }
        if(areaId!=='accrued_verify' && areaId!=='er_bxcontrast'){
            returnObj[areaId +'_Delete']={
                beforeClick:(record, index) => {
                    console.log('before delete record:');
                    if((record.status == '1' || record.status == '0')&& record.values.pk_mtapp_detail&& record.values.pk_mtapp_detail.value) {
                        toast({content:'由申请生成的报销明细不允许删除,请知悉!', color:'danger'})
                        return false
                    }
                    return true
                },
                afterClick: (...args) => {
                    headSumHandle.call(this, args, 'delete', areaId);
                }
            };
            returnObj[areaId +'_Copy']={
                afterClick: (record, index) => {
                    clearPropsAboutInvoices.call(this, areaId, index+1)
                    headSumHandle.call(this);
                }
            };

            returnObj[areaId + '_Attachment'] = {
                afterClick: (record, index) => {
                    showTableAttachment.call(this, record, index)
                }
            };
            returnObj[areaId + '_Edit'] = {
                afterClick: (record, index) => {
                    // 切换展开/收起按钮
                    if (record) {
                        if (record.expandRowStatus) { // 收起
                            let elem = document.querySelector(`.u-table-fixed-right tr[data-row-key='${record.rowid}'] a.row-btn-${areaId}_Edit`);
                            elem.innerHTML = '收起';
                        } else { // 展开
                            let elem = document.querySelector(`.u-table-fixed-right tr[data-row-key='${record.rowid}'] a.row-btn-${areaId}_Edit`);
                            elem.innerHTML = '展开';
                        }
                    }
                }
            };
            returnObj[areaId + '_Insert'] = {
                afterClick: (record, index) => {
                    clearPropsAboutInvoices.call(this, areaId, index+1)
                    setDefautValueAfterBodyAdd.call(this, this.props, areaId, index, true);
                }
            };
        }
    }
    return returnObj;
}

//清空发票相关的字段,处理行数据,模板没有的字段,使用setValByKeyAndIndex是无法清空的
export function clearPropsAboutInvoices(tableCode, index) {
    const filterKeys = [ "pk_erminvoice", "pk_erminvoice_b", "fphm", "fpdm", "fplxpk"]
    const tableData = this.props.cardTable.getVisibleRows(tableCode)
    if(tableData[index] && tableData[index].values) {
        let obj = {...tableData[index].values }
        filterKeys.forEach(key => {
            obj[key] = {display: null, value: null}
        })
        tableData[index].values = obj
    }
    this.props.cardTable.setTableDataWithResetInitValue(tableCode, {rows: tableData})
}

function showTableAttachment(record, index) {
    console.log('record:', record, index)
    const props = this.props;
    let billId = props.getUrlParam('billid') || this.state.billId || "";
    let billtype = window.presetVar.tradetype || "";

    const params = {}
    if(record.values.pk_busitem) params.pk_busitem = record.values.pk_busitem.value
    if(record.values.pk_erminvoice) params.pk_erminvoice = record.values.pk_erminvoice.value
    if(record.values.generatetype) params.generatetype = record.values.generatetype.value

    if (billId == "" && !this.state.showTableUploader){
        //去后台生成单据主键
        requestApi.generatBillId({
            data: {billtype: billtype},
            success:(data)=>{
                let accessorypkfildname = data["pkfieldName"];
                billId = data[accessorypkfildname];
                setTimeout(() => {
                    this.setState({
                        billId: billId ,
                        showTableUploader: !this.state.showTableUploader,
                        reqTableAttachParam: params
                    });
                })

                this.accessorybillid = billId;
            },
            error:(data)=>{
                toast({ content: data.message, color: 'danger' });
            }
        });
    } else {
        setTimeout(() => {
            this.setState({
                billId: billId ,
                showTableUploader: !this.state.showTableUploader,
                reqTableAttachParam: params
            });
        })
    }
}

export default tableExtendButtonClick;
